/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.module.web;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.pajamas.starter.core.vo.PajamasValidStrategy;
import org.pajamas.starter.core.vo.PajamasValidationException;
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

/**
 * @author william
 * @since 2024/1/14
 */

public class PajamasMethodValidationAdvice implements MethodBeforeAdvice {
    private static Pair<Integer, PajamasValidStrategy> extractValidatedArg(Method method) {
        Annotation[][] parametersAnnotations = method.getParameterAnnotations();
        Pair<Integer, PajamasValidStrategy> validatedArg = null;
        for (int idx = 0; idx < parametersAnnotations.length; idx++) {
            Annotation[] parameterAnnotations = parametersAnnotations[idx];
            if (ArrayUtils.isEmpty(parameterAnnotations)) {
                continue;
            }
            List<PajamasValidStrategy> annotations = Arrays.stream(parameterAnnotations)
                    .filter(Objects::nonNull)
                    .filter(annotation -> {
                        Class<? extends Annotation> annotationClass = annotation.annotationType();
                        return PajamasValidStrategy.class.equals(annotationClass);
                    })
                    .map(PajamasValidStrategy.class::cast)
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(annotations)) {
                continue;
            }
            if (annotations.size() > 1) {
                throw new PajamasValidatedArgsException("extractValidatedArg.annotations.size over 1");
            }
            if (validatedArg != null) {
                throw new PajamasValidatedArgsException("extractValidatedArg.validatedArg over 1");
            }
            validatedArg = Pair.of(idx, annotations.get(0));
        }
        return validatedArg;
    }

    @SuppressWarnings("NullableProblems")
    @Override
    public void before(Method method, Object[] args, Object target) {
        Pair<Integer, PajamasValidStrategy> validatedArgMap = extractValidatedArg(method);
        if (validatedArgMap == null) {
            return;
        }
        Integer argsIdx = validatedArgMap.getKey();
        PajamasValidStrategy annotation = validatedArgMap.getValue();
        Validator validator = annotation.validator().getValidator();
        Class<?>[] groups = annotation.groups();
        Object validatedArg = args[argsIdx];
        Set<ConstraintViolation<Object>> violations = validator.validate(validatedArg, groups);
        if (CollectionUtils.isNotEmpty(violations)) {
            throw new PajamasValidationException(violations);
        }
    }
}
